import type { GetServerSideProps, NextPage } from 'next'
import Head from 'next/head'
import router from 'next/router'
import styles from '../styles/Home.module.scss'
import { useState } from 'react'

import { InfiniteScroll } from 'antd-mobile'

import Nav from '../components/Nav'
import Searchbar from '../components/Searchbar'
import { BookService } from '../services'
import { Blist } from '../services/book.service'
import { useMount } from 'ahooks'
import Empty from '../components/Empty'
import { judgeLoad, uniqueFunc } from '../libs/utils'
import Mainlist from '../components/Mainlist'

interface Props {
  booklist: Blist[]
  total: number
}

export const getServerSideProps: GetServerSideProps = async ctx => {
  const res = await BookService.indexlist(0, 10)
  if (res.stat === 'OK')
    return {
      props: {
        booklist: res.data.list,
        total: res.data.total
      }
    }
  return {
    props: {
      booklist: [],
      total: 0
    }
  }
}

const pageSize = 10

const Home: NextPage<Props> = ({ booklist, total }) => {
  const [books, SetBooks] = useState(booklist)
  const [hasMore, setHasMore] = useState<boolean>(true)

  useMount(() => {
    SetBooks(booklist)
  })

  async function getList(offset: number) {
    const res = await BookService.indexlist(offset, pageSize)
    if (res.stat === 'OK') {
      const newList = res.data.list
      SetBooks(oldList => {
        const total = oldList.length + newList.length
        setHasMore(total < res.data.total)
        return uniqueFunc([...oldList, ...newList]) as BookService.Blist[]
      })
    }
  }

  return (
    <div className="page">
      <Head>
        <title>民大二手书店</title>
      </Head>
      <div className={styles.wrap}>
        <header className={styles.top}>
          <Searchbar page='index' send={(v: string) => { }} />
        </header>
        <main className={styles.bookwrap}>
          {
            books.map((item, idx) => {
              return <div key={item._id} >
                <Mainlist book={item} />
              </div>
            })
          }
        </main>
        {total === 0 && <Empty />}
        {
          !judgeLoad(books, hasMore) &&
          <InfiniteScroll
            loadMore={() => getList(books.length)}
            hasMore={hasMore}
          />
        }
      </div>
      <Nav active={1} />
    </div>
  )
}

export default Home
